package com.foreveross.bsl.push.web;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.foreveross.bsl.common.utils.mapper.BeanMapper;
import com.foreveross.bsl.mam.app.application.AppMainApplication;
import com.foreveross.bsl.mam.app.application.vo.AppMainVo;
import com.foreveross.bsl.mam.model.application.WidgetApplication;
import com.foreveross.bsl.mam.model.application.vo.WidgetVO;
import com.foreveross.bsl.push.application.AppChannelConfigService;
import com.foreveross.bsl.push.application.PushService;
import com.foreveross.bsl.push.application.TagSummaryService;
import com.foreveross.bsl.push.application.vo.MessageParams;
import com.foreveross.bsl.push.application.vo.MessageVo;
import com.foreveross.bsl.push.application.vo.ModuleMessage;
import com.foreveross.bsl.push.application.vo.TagSummaryVo;
import com.foreveross.bsl.push.form.MessageSubmitForm;
import com.foreveross.bsl.system.application.ApplicationRegisterApplication;
import com.foreveross.bsl.web.ApplicationException;
import com.google.common.collect.Maps;

@Controller
@RequestMapping(value = "/push")
public class PushController extends PushBaseController {

    @Inject
	private PushService pushService;

	@Inject
	private TagSummaryService tagSumService;

	@Inject
	private AppMainApplication appService;
	
	@Inject
	private WidgetApplication moduleService;
	
	@Inject
	private AppChannelConfigService configService;
	
	@Inject
	private ApplicationRegisterApplication appRegClient;
	
	/** 检查应用是否有推送渠道
	 * @param appId
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String creatForm(@RequestParam("appId") String appId, Model model, RedirectAttributes redirectAttributes) {
		AppMainVo app = appService.getEntity(appId);
		if (app == null) {
			throw new ApplicationException("不存在应用：" + appId);
		}
		String appKey = this.appRegClient.getAppKeyByAppId(appId);
		if(appKey == null){
			throw new ApplicationException("无法通过appId:" + appId + "获取其对应的appKey");
		}
		if(this.configService.existsConfig(appKey)) {
			TagSummaryVo tagSum = this.tagSumService.getTagSummary(appKey);
			List<WidgetVO> modules = this.moduleService.getWidgetsForRbac(appId);
			this.filterSpecifiedModules(modules);
			model.addAttribute("tagSum", tagSum);
			model.addAttribute("msg", new MessageVo());
			model.addAttribute("appId", appId);
			model.addAttribute("appKey", appKey);
			model.addAttribute("app", app);
			model.addAttribute("modules", modules);
			return "push/push-form";
		} else { // 没有配置过推送渠道的情况
			redirectAttributes.addAttribute("appId", appId);
			redirectAttributes.addAttribute("appKey", appKey);
			redirectAttributes.addAttribute("create", true); // 创建
			redirectAttributes.addAttribute("redirect", "redirect:/push/create");
			return "redirect:/push/config/channel";
		}
	}
	
	/**
	 * 过虑掉特殊的模块，包括:设为隐藏的模块、即时通讯、消息和公告模块
	 * @param modules
	 */
	private void filterSpecifiedModules(List<WidgetVO> modules){
		//分别依次对应模块：即时通讯、消息和公告模块
		final String[] filters={"com.foss.chat","com.foss.message.record","com.foss.announcement"};
		Iterator<WidgetVO> it=modules.iterator();
		while(it.hasNext()){
			WidgetVO m=it.next();
			if(m.isHidden()){
				it.remove();
				continue;
			}
			for(String f : filters){
				if(f.equals(m.getIdentify())){
					it.remove();
					break;
				}
			}
		}
	}

	@RequestMapping(value = "create", method = RequestMethod.POST, produces={"application/json"})
	public @ResponseBody Map<String, Object> create(MessageSubmitForm form) {
		MessageParams msgParams=BeanMapper.map(form, MessageParams.class);
		if(form.getExtras()!=null){
			Map<String, Object> extras=form.getExtras();
			String str=(String)extras.get("moduleBadge");
			if("on".equals(str)){
				extras.put("moduleBadge", true);
			}
			str=(String)extras.get("busiDetail");
			if("on".equals(str)){
				extras.put("busiDetail", true);
			}
			msgParams.getMessage().setExtras(extras);
		}
		msgParams.setAppId(form.getAppKey());
		msgParams.validate();
		if(MessageVo.MessageTypeEnum.MODULE.equals(msgParams.getMessage().getMessageType())){
			if(StringUtils.isEmpty(form.getModuleIdentifer())){
				throw new IllegalArgumentException("模块消息的moduleIdentifer不能为空");
			}
			msgParams.getMessage().putExtra(ModuleMessage.KEY_MODULE_ID, form.getModuleIdentifer());
			msgParams.getMessage().putExtra(ModuleMessage.KEY_MODULE_NAME, form.getModuleName());
		}
		msgParams.setSubmitUserId(this.getCurrentUserId());
		String pushRequestId=this.pushService.submitMessage(msgParams);
		Map<String, Object> result=Maps.newHashMap();
		result.put("result", true);
		result.put("pushRequestId", pushRequestId);
		return result;
	}
}